package com.hyjoy.dao.impl;

import com.hyjoy.dao.OrderDao;
import com.hyjoy.entity.Order;
import com.hyjoy.entity.OrderItem;
import com.hyjoy.entity.PageBean;
import com.hyjoy.entity.Product;
import com.hyjoy.util.DataSourceUtils;
import com.hyjoy.util.StringUtils;
import com.sun.xml.internal.bind.v2.model.core.ID;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.util.List;
import java.util.Map;

public class OrderDaoImpl implements OrderDao {

    @Override
    /**
     * 保存订单
     */
    public void save(Order o) throws Exception {
        QueryRunner qr = new QueryRunner();
        /**
         * `oid` varchar(32) NOT NULL,
         `ordertime` datetime DEFAULT NULL,
         `total` double DEFAULT NULL,

         `state` int(11) DEFAULT NULL,
         `address` varchar(30) DEFAULT NULL,
         `name` varchar(20) DEFAULT NULL,

         `telephone` varchar(20) DEFAULT NULL,
         `uid` varchar(32) DEFAULT NULL,
         */
        String sql = "insert into orders values(?,?,?,?,?,?,?,?)";
        qr.update(DataSourceUtils.getConnection(), sql, o.getOid(), o.getOrdertime(), o.getTotal(),
                o.getState(), o.getAddress(), o.getName(),
                o.getTelephone(), o.getUser().getUid());
    }

    @Override
    /**
     * 保存订单项
     */
    public void saveItem(OrderItem oi) throws Exception {
        QueryRunner qr = new QueryRunner();
		/*
		 * `itemid` varchar(32) NOT NULL,
				  `count` int(11) DEFAULT NULL,
				  `subtotal` double DEFAULT NULL,
				  
				  `pid` varchar(32) DEFAULT NULL,
				  `oid` varchar(32) DEFAULT NULL,
		 */
        String sql = "insert into orderitem values(?,?,?,?,?)";
        qr.update(DataSourceUtils.getConnection(), sql, oi.getItemid(), oi.getCount(), oi.getSubtotal(),
                oi.getProduct().getPid(), oi.getOrder().getOid());
    }

    @Override
    public int getTotalRecord(String uid) throws Exception {
        QueryRunner queryRunner = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "select count(*) from orders where uid = ?";
        return ((Long) queryRunner.query(sql, new ScalarHandler(), uid)).intValue();
    }

    @Override
    public List<Order> findMyOrdersByPage(PageBean<Order> pb, String uid) throws Exception {
        QueryRunner queryRunner = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "select * from orders where uid = ? order by ordertime desc limit ?, ?";
        List<Order> list = queryRunner.query(sql, new BeanListHandler<Order>(Order.class), uid, pb.getStartIndex(), pb.getPageSize());

        for (Order order : list) {
            sql = "select * from orderitem oi, product p where oi.pid = p.pid and oi.oid = ?";
            List<Map<String, Object>> mapList = queryRunner.query(sql, new MapListHandler(), order.getOid());
            // 遍历maplist, 获取每一个订单项详情，封装成orderitem，将其加入当前订单项列表
            for (Map<String, Object> map : mapList) {
                OrderItem orderItem = new OrderItem();
                BeanUtils.populate(orderItem, map);
                Product product = new Product();
                BeanUtils.populate(product, map);
                orderItem.setProduct(product);

                order.getItems().add(orderItem);
            }
        }
        return list;
    }

    @Override
    public Order getById(String oid) throws Exception {
        QueryRunner queryRunner = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "select * from orders where oid = ?";
        Order order = queryRunner.query(sql, new BeanHandler<>(Order.class), oid);
        sql = "select * from orderitem oi, product p where oi.pid = p.pid and oi.oid = ?";
        List<Map<String, Object>> mapList = queryRunner.query(sql, new MapListHandler(), oid);

        for (Map<String, Object> map : mapList) {
            OrderItem orderItem = new OrderItem();
            BeanUtils.populate(orderItem, map);
            Product product = new Product();
            BeanUtils.populate(product, map);

            orderItem.setProduct(product);
            order.getItems().add(orderItem);
        }
        return order;
    }

    @Override
    public void update(Order order) throws Exception {
        QueryRunner queryRunner = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "update orders set state = ? , address = ? , name = ? , telephone = ? where oid = ?";
        queryRunner.update(sql, order.getState(), order.getAddress(), order.getName(), order.getTelephone(), order.getOid());
    }

    @Override
    public List<Order> findAllByState(String state) throws Exception {
        QueryRunner queryRunner = new QueryRunner(DataSourceUtils.getDataSource());

        String sql = "select * from orders";
        if (StringUtils.isTrimEmpty(state)) {
            sql += " order by ordertime desc";
            return queryRunner.query(sql, new BeanListHandler<>(Order.class));
        }
        sql += " where state = ? order by ordertime desc";
        return queryRunner.query(sql, new BeanListHandler<>(Order.class), state);
    }

}
